<template>
  <div class="data-object-container p-4">
    <!-- 页面标题 -->
    <div class="page-header flex justify-between items-center mb-5">
      <div>
        <h2 class="text-2xl font-bold mb-1 flex items-center">
          <div class="i-carbon-data-table text-primary mr-2 text-3xl"></div>
          数据对象管理
        </h2>
        <p class="text-gray-500 text-sm">管理各个数据源中的表、视图等数据对象</p>
      </div>
      <div class="flex gap-2">
        <el-button type="success" @click="handleCollect" class="flex items-center">
          <div class="i-carbon-data-refinery mr-1"></div>采集元数据
        </el-button>
        <el-button type="primary" @click="handleAdd" class="flex items-center">
          <div class="i-carbon-add mr-1"></div>手动创建
        </el-button>
      </div>
    </div>

    <div class="flex gap-4">
      <!-- 左侧数据源树和分类树 -->
      <div class="w-64 flex-none">
        <el-card class="border-0 shadow-sm mb-4">
          <template #header>
            <div class="flex items-center">
              <div class="i-carbon-data-base text-primary mr-2"></div>
              <span>数据源列表</span>
            </div>
          </template>
          <el-input
            v-model="dataSourceSearch"
            placeholder="搜索数据源"
            prefix-icon="Search"
            clearable
            class="mb-2"
          />
          <el-tree
            ref="dataSourceTreeRef"
            :data="dataSourceTree"
            :props="defaultProps"
            :filter-node-method="filterDataSourceNode"
            highlight-current
            node-key="id"
            @node-click="handleDataSourceSelect"
          >
            <template #default="{ node, data }">
              <div class="flex items-center">
                <div :class="getNodeIcon(data)" class="mr-1"></div>
                <span>{{ node.label }}</span>
                <span v-if="data.type === 'source'" class="ml-1 text-xs text-gray-400">({{ data.objectCount }})</span>
              </div>
            </template>
          </el-tree>
        </el-card>

        <el-card class="border-0 shadow-sm">
          <template #header>
            <div class="flex items-center">
              <div class="i-carbon-category text-primary mr-2"></div>
              <span>对象分类</span>
            </div>
          </template>
          <el-tabs v-model="categoryTabActive" class="category-tabs">
            <el-tab-pane label="业务分类" name="business">
              <el-tree
                :data="businessCategoryTree"
                :props="defaultProps"
                highlight-current
                node-key="id"
                @node-click="handleCategorySelect"
              >
                <template #default="{ node }">
                  <div class="flex items-center">
                    <div class="i-carbon-folder text-primary mr-1"></div>
                    <span>{{ node.label }}</span>
                  </div>
                </template>
              </el-tree>
            </el-tab-pane>
            <el-tab-pane label="技术分类" name="technical">
              <el-tree
                :data="technicalCategoryTree"
                :props="defaultProps"
                highlight-current
                node-key="id"
                @node-click="handleCategorySelect"
              >
                <template #default="{ node }">
                  <div class="flex items-center">
                    <div class="i-carbon-folder text-primary mr-1"></div>
                    <span>{{ node.label }}</span>
                  </div>
                </template>
              </el-tree>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>

      <!-- 右侧主区域 -->
      <div class="flex-1">
        <!-- 搜索条件区 -->
        <el-card class="mb-4 border-0 shadow-sm">
          <el-form :inline="true" :model="searchForm" class="flex flex-wrap">
            <el-form-item label="对象名称">
              <el-input v-model="searchForm.objectName" placeholder="请输入对象名称" clearable />
            </el-form-item>
            <el-form-item label="对象类型">
              <el-select v-model="searchForm.objectType" placeholder="请选择对象类型" clearable>
                <el-option v-for="item in objectTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" class="flex items-center">
                <div class="i-carbon-search mr-1"></div>查询
              </el-button>
              <el-button @click="handleReset" class="flex items-center">
                <div class="i-carbon-reset mr-1"></div>重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 数据列表区 -->
        <el-card class="border-0 shadow-sm">
          <div class="flex justify-between mb-3">
            <div class="flex items-center">
              <template v-if="currentDataSource">
                <div :class="getDbTypeIcon(currentDataSource.type)" class="mr-2 text-lg"></div>
                <span class="font-medium mr-2">{{ currentDataSource.label }}</span>
                <el-tag>{{ getDbTypeLabel(currentDataSource.type) }}</el-tag>
              </template>
              <template v-else-if="currentCategory">
                <div class="i-carbon-folder text-primary mr-2"></div>
                <span class="font-medium">{{ currentCategory.label }}</span>
              </template>
              <template v-else>
                <div class="i-carbon-list-checked text-primary mr-2"></div>
                <span class="font-medium">数据对象列表</span>
              </template>
              <el-tag class="ml-2" type="info">总计 {{ total }} 条</el-tag>
            </div>
            <div>
              <el-button @click="handleSync" class="flex items-center" v-if="currentDataSource">
                <div class="i-carbon-renew mr-1"></div>同步
              </el-button>
            </div>
          </div>

          <el-table v-loading="loading" :data="tableData" border style="width: 100%" row-key="id" class="mt-2">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="objectName" label="对象名称" min-width="150">
              <template #default="{ row }">
                <div class="flex items-center">
                  <div :class="getObjectTypeIcon(row.objectType)" class="mr-2 text-lg"></div>
                  <el-link type="primary" @click="handleView(row)">{{ row.objectName }}</el-link>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="objectType" label="对象类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getObjectTypeTagType(row.objectType)">
                  {{ getObjectTypeLabel(row.objectType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="dataSourceName" label="所属数据源" width="150" />
            <el-table-column prop="schemaName" label="模式/数据库" width="120" />
            <el-table-column prop="businessCategory" label="业务分类" width="120" />
            <el-table-column prop="technicalCategory" label="技术分类" width="120" />
            <el-table-column prop="columnCount" label="字段数" width="80" align="center" />
            <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />
            <el-table-column label="操作" width="240" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEdit(row)" class="flex items-center">
                  <div class="i-carbon-edit mr-1"></div>编辑
                </el-button>
                <el-button type="primary" link @click="handleViewColumns(row)" class="flex items-center">
                  <div class="i-carbon-column mr-1"></div>字段信息
                </el-button>
                <el-button type="primary" link @click="handleViewLineage(row)" class="flex items-center">
                  <div class="i-carbon-flow mr-1"></div>血缘关系
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)" class="flex items-center">
                  <div class="i-carbon-trash-can mr-1"></div>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="flex justify-end mt-4">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.id ? '编辑数据对象' : '创建数据对象'"
      width="650px"
      destroy-on-close
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
        class="mt-2"
      >
        <el-tabs v-model="activeEditTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="对象名称" prop="objectName">
                  <el-input v-model="editForm.objectName" placeholder="请输入对象名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="对象类型" prop="objectType">
                  <el-select v-model="editForm.objectType" placeholder="请选择对象类型" style="width: 100%">
                    <el-option 
                      v-for="item in objectTypeOptions" 
                      :key="item.value" 
                      :label="item.label" 
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属数据源" prop="dataSourceId">
                  <el-select 
                    v-model="editForm.dataSourceId" 
                    placeholder="请选择数据源" 
                    style="width: 100%"
                    @change="handleDataSourceChange"
                  >
                    <el-option
                      v-for="item in dataSourceOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                      <div class="flex items-center">
                        <div :class="getDbTypeIcon(item.type)" class="mr-2"></div>
                        <span>{{ item.name }}</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="模式/数据库" prop="schemaName">
                  <el-input v-model="editForm.schemaName" placeholder="请输入模式名/数据库名" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="业务分类">
                  <el-cascader
                    v-model="editForm.businessCategory"
                    :options="businessCategoryOptions"
                    :props="{ checkStrictly: true }"
                    placeholder="请选择业务分类"
                    clearable
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="技术分类">
                  <el-cascader
                    v-model="editForm.technicalCategory"
                    :options="technicalCategoryOptions"
                    :props="{ checkStrictly: true }"
                    placeholder="请选择技术分类"
                    clearable
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="描述" prop="description">
              <el-input 
                v-model="editForm.description" 
                type="textarea" 
                :rows="3" 
                placeholder="请输入数据对象的描述信息" 
              />
            </el-form-item>
          </el-tab-pane>

          <!-- 字段信息预览 -->
          <el-tab-pane label="字段信息" name="columns">
            <div class="flex justify-between mb-3">
              <div>
                <el-button type="primary" size="small" @click="addColumn" class="flex items-center">
                  <div class="i-carbon-add mr-1"></div>添加字段
                </el-button>
              </div>
              <div v-if="editForm.objectType === 'TABLE' || editForm.objectType === 'VIEW'">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="goToDetailForColumns" 
                  class="flex items-center"
                >
                  <div class="i-carbon-arrow-right mr-1"></div>高级编辑
                </el-button>
              </div>
            </div>
            
            <el-table :data="editForm.columns" border style="width: 100%">
              <el-table-column type="index" width="50" align="center" />
              <el-table-column prop="name" label="字段名" min-width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.name" placeholder="字段名" size="small" />
                </template>
              </el-table-column>
              <el-table-column prop="type" label="数据类型" width="120">
                <template #default="{ row, $index }">
                  <el-select v-model="row.type" placeholder="类型" size="small" style="width: 100%">
                    <el-option label="VARCHAR" value="VARCHAR" />
                    <el-option label="CHAR" value="CHAR" />
                    <el-option label="TEXT" value="TEXT" />
                    <el-option label="INTEGER" value="INTEGER" />
                    <el-option label="BIGINT" value="BIGINT" />
                    <el-option label="DECIMAL" value="DECIMAL" />
                    <el-option label="DOUBLE" value="DOUBLE" />
                    <el-option label="DATE" value="DATE" />
                    <el-option label="DATETIME" value="DATETIME" />
                    <el-option label="TIMESTAMP" value="TIMESTAMP" />
                    <el-option label="BOOLEAN" value="BOOLEAN" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="length" label="长度" width="80">
                <template #default="{ row, $index }">
                  <el-input v-model="row.length" placeholder="长度" size="small" />
                </template>
              </el-table-column>
              <el-table-column prop="nullable" label="可空" width="70" align="center">
                <template #default="{ row, $index }">
                  <el-checkbox v-model="row.nullable" />
                </template>
              </el-table-column>
              <el-table-column prop="isPk" label="主键" width="70" align="center">
                <template #default="{ row, $index }">
                  <el-checkbox v-model="row.isPk" />
                </template>
              </el-table-column>
              <el-table-column prop="comment" label="备注" min-width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.comment" placeholder="备注" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template #default="{ $index }">
                  <el-button 
                    type="danger" 
                    link 
                    @click="removeColumn($index)" 
                    size="small"
                    class="flex items-center"
                  >
                    <div class="i-carbon-trash-can"></div>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <div class="text-center text-sm text-gray-500 mt-3" v-if="editForm.columns.length === 0">
              还没有添加字段，点击上方"添加字段"按钮开始添加
            </div>
            
            <div class="text-right mt-3" v-if="editForm.columns.length > 5">
              <el-button 
                type="primary" 
                size="small" 
                @click="goToDetailForColumns" 
                class="flex items-center ml-auto"
              >
                <div class="i-carbon-arrow-right mr-1"></div>高级字段编辑
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="saveObject" :loading="submitLoading">保存</el-button>
      </template>
    </el-dialog>

    <!-- 采集元数据对话框 -->
    <el-dialog v-model="collectDialogVisible" title="采集元数据" width="600px">
      <el-form :model="collectForm" label-width="100px">
        <el-form-item label="数据源">
          <el-select v-model="collectForm.dataSourceId" placeholder="请选择数据源" style="width: 100%">
            <el-option
              v-for="item in dataSourceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div class="flex items-center">
                <div :class="getDbTypeIcon(item.type)" class="mr-2"></div>
                <span>{{ item.name }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="采集内容">
          <el-checkbox-group v-model="collectForm.objectTypes">
            <el-checkbox label="TABLE">表</el-checkbox>
            <el-checkbox label="VIEW">视图</el-checkbox>
            <el-checkbox label="PROCEDURE">存储过程</el-checkbox>
            <el-checkbox label="FUNCTION">函数</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="过滤条件">
          <el-input v-model="collectForm.filter" placeholder="请输入对象名称过滤条件，支持*通配符" />
        </el-form-item>
        
        <el-form-item label="业务分类">
          <el-cascader
            v-model="collectForm.businessCategory"
            :options="businessCategoryOptions"
            :props="{ checkStrictly: true }"
            placeholder="请选择业务分类"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="技术分类">
          <el-cascader
            v-model="collectForm.technicalCategory"
            :options="technicalCategoryOptions"
            :props="{ checkStrictly: true }"
            placeholder="请选择技术分类"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="collectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCollect" :loading="collectLoading">开始采集</el-button>
      </template>
    </el-dialog>

    <!-- 采集进度对话框 -->
    <el-dialog v-model="progressDialogVisible" title="采集进度" width="500px" :close-on-click-modal="false">
      <div class="text-center mb-4">
        <div v-if="collectProgress < 100" class="i-carbon-data-refinery text-primary text-5xl animate-pulse"></div>
        <div v-else class="i-carbon-checkmark-filled text-green-500 text-5xl"></div>
      </div>
      
      <el-progress :percentage="collectProgress" :status="collectProgress === 100 ? 'success' : ''"></el-progress>
      
      <div class="text-center mt-4">
        <div v-if="collectProgress < 100">正在采集元数据，已完成 {{ collectProgress }}%</div>
        <div v-else>元数据采集完成，共采集 {{ collectResult.total }} 个对象</div>
      </div>
      
      <div v-if="collectProgress === 100" class="mt-4">
        <div class="flex justify-between text-sm text-gray-500 mb-2">
          <div>表：{{ collectResult.table }} 个</div>
          <div>视图：{{ collectResult.view }} 个</div>
          <div>存储过程：{{ collectResult.procedure }} 个</div>
          <div>函数：{{ collectResult.function }} 个</div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="progressDialogVisible = false" :disabled="collectProgress < 100 && !collectFailed">
          {{ collectProgress < 100 && !collectFailed ? '采集中...' : '关闭' }}
        </el-button>
        <el-button type="primary" @click="refreshList" v-if="collectProgress === 100">刷新列表</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ElTree } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 数据对象类型选项
const objectTypeOptions = [
  { label: '表', value: 'TABLE' },
  { label: '视图', value: 'VIEW' },
  { label: '存储过程', value: 'PROCEDURE' },
  { label: '函数', value: 'FUNCTION' },
  { label: '触发器', value: 'TRIGGER' },
  { label: '序列', value: 'SEQUENCE' },
]

// 列表数据
const tableData = ref<any[]>([])
const loading = ref(false)
const total = ref(0)

// 搜索条件
const searchForm = reactive({
  objectName: '',
  objectType: '',
  dataSourceId: '',
  categoryId: '',
  categoryType: '',
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
})

// 数据源树
const dataSourceTreeRef = ref<InstanceType<typeof ElTree>>()
const dataSourceSearch = ref('')
const dataSourceTree = ref<any[]>([])
const currentDataSource = ref<any>(null)
const currentCategory = ref<any>(null)
const defaultProps = {
  children: 'children',
  label: 'label',
}

// 对象分类相关
const categoryTabActive = ref('business')
const businessCategoryTree = ref<any[]>([])
const technicalCategoryTree = ref<any[]>([])

// 元数据采集相关
const collectDialogVisible = ref(false)
const progressDialogVisible = ref(false)
const collectLoading = ref(false)
const collectProgress = ref(0)
const collectFailed = ref(false)
const collectResult = reactive({
  total: 0,
  table: 0,
  view: 0,
  procedure: 0,
  function: 0,
})

const collectForm = reactive({
  dataSourceId: '',
  objectTypes: ['TABLE', 'VIEW'],
  filter: '',
  businessCategory: '',
  technicalCategory: '',
})

// 数据源选项
const dataSourceOptions = ref<any[]>([])

// 业务分类和技术分类选项
const businessCategoryOptions = ref<any[]>([])
const technicalCategoryOptions = ref<any[]>([])

// 编辑弹窗相关
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const activeEditTab = ref('basic')
const submitLoading = ref(false)

// 编辑表单
const defaultEditForm = {
  id: '',
  objectName: '',
  objectType: 'TABLE',
  dataSourceId: '',
  dataSourceName: '',
  dataSourceType: '',
  schemaName: '',
  businessCategory: '',
  technicalCategory: '',
  description: '',
  columns: [] as any[]
}

const editForm = reactive({ ...defaultEditForm })

// 表单验证规则
const editRules = {
  objectName: [
    { required: true, message: '请输入对象名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  objectType: [
    { required: true, message: '请选择对象类型', trigger: 'change' }
  ],
  dataSourceId: [
    { required: true, message: '请选择所属数据源', trigger: 'change' }
  ]
}

// 数据源变更处理
const handleDataSourceChange = (value: string) => {
  const selectedSource = dataSourceOptions.value.find(item => item.id === value)
  if (selectedSource) {
    editForm.dataSourceName = selectedSource.name
    editForm.dataSourceType = selectedSource.type
  }
}

// 添加字段
const addColumn = () => {
  editForm.columns.push({
    name: '',
    type: 'VARCHAR',
    length: '255',
    nullable: true,
    isPk: false,
    comment: ''
  })
}

// 删除字段
const removeColumn = (index: number) => {
  editForm.columns.splice(index, 1)
}

// 监听数据源搜索
watch(dataSourceSearch, (val) => {
  dataSourceTreeRef.value?.filter(val)
})

// 过滤数据源节点
const filterDataSourceNode = (value: string, data: any) => {
  if (!value) return true
  return data.label.toLowerCase().includes(value.toLowerCase())
}

// 获取节点图标
const getNodeIcon = (data: any) => {
  if (data.type === 'root') {
    return 'i-carbon-database'
  } else if (data.type === 'source') {
    return getDbTypeIcon(data.dbType)
  } else {
    return 'i-carbon-folder'
  }
}

// 根据数据库类型获取图标
const getDbTypeIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    'MySQL': 'i-logos-mysql',
    'Oracle': 'i-logos-oracle',
    'SQLServer': 'i-logos-microsoft',
    'PostgreSQL': 'i-logos-postgresql',
    'MongoDB': 'i-logos-mongodb',
    'Redis': 'i-logos-redis',
    'Hive': 'i-logos-hadoop',
    'HBase': 'i-logos-hbase',
  }
  return iconMap[type] || 'i-carbon-data-base'
}

// 根据数据库类型获取标签文本
const getDbTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    'MySQL': 'MySQL',
    'Oracle': 'Oracle',
    'SQLServer': 'SQL Server',
    'PostgreSQL': 'PostgreSQL',
    'MongoDB': 'MongoDB',
    'Redis': 'Redis',
    'Hive': 'Hive',
    'HBase': 'HBase',
  }
  return typeMap[type] || type
}

// 根据对象类型获取图标
const getObjectTypeIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    'TABLE': 'i-carbon-table',
    'VIEW': 'i-carbon-view',
    'PROCEDURE': 'i-carbon-function',
    'FUNCTION': 'i-carbon-function-math',
    'TRIGGER': 'i-carbon-reminder',
    'SEQUENCE': 'i-carbon-circle-packing',
  }
  return iconMap[type] || 'i-carbon-document'
}

// $h 根据对象类型获取标签类型
const getObjectTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'TABLE': '',
    'VIEW': 'success',
    'PROCEDURE': 'warning',
    'FUNCTION': 'warning',
    'TRIGGER': 'info',
    'SEQUENCE': 'info',
  }
  return typeMap[type] || ''
}

// 根据对象类型获取标签文本
const getObjectTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    'TABLE': '表',
    'VIEW': '视图',
    'PROCEDURE': '存储过程',
    'FUNCTION': '函数',
    'TRIGGER': '触发器',
    'SEQUENCE': '序列',
  }
  return typeMap[type] || type
}

// 初始化数据源树
const initDataSourceTree = () => {
  // 模拟数据源数据
  const mockDataSources = Array.from({ length: 8 }).map((_, index) => {
    const id = `ds_${index + 1}`
    const dbTypeIndex = index % 8
    const dbTypeOptions = [
      'MySQL', 'Oracle', 'SQLServer', 'PostgreSQL', 
      'MongoDB', 'Redis', 'Hive', 'HBase'
    ]
    const dbType = dbTypeOptions[dbTypeIndex]
    const name = `${dbType}数据源${index + 1}`
    const objectCount = Math.floor(Math.random() * 100) + 10
    
    return {
      id,
      label: name,
      type: 'source',
      dbType,
      objectCount,
    }
  })
  
  dataSourceTree.value = [
    {
      id: 'root',
      label: '全部数据源',
      type: 'root',
      children: mockDataSources
    }
  ]
  
  // 构建数据源选项
  dataSourceOptions.value = mockDataSources.map(ds => ({
    id: ds.id,
    name: ds.label,
    type: ds.dbType
  }))
}

// 初始化分类树
const initCategoryTree = () => {
  // 业务分类树
  businessCategoryTree.value = [
    {
      id: 'bc_1',
      label: '销售管理',
      children: [
        { id: 'bc_1_1', label: '订单管理' },
        { id: 'bc_1_2', label: '客户管理' },
        { id: 'bc_1_3', label: '合同管理' },
      ]
    },
    {
      id: 'bc_2',
      label: '生产管理',
      children: [
        { id: 'bc_2_1', label: '生产计划' },
        { id: 'bc_2_2', label: '生产执行' },
      ]
    },
    {
      id: 'bc_3',
      label: '库存管理',
      children: [
        { id: 'bc_3_1', label: '入库管理' },
        { id: 'bc_3_2', label: '出库管理' },
        { id: 'bc_3_3', label: '库存盘点' },
      ]
    },
    {
      id: 'bc_4',
      label: '财务管理',
      children: [
        { id: 'bc_4_1', label: '财务核算' },
        { id: 'bc_4_2', label: '费用管理' },
      ]
    },
  ]
  
  // 技术分类树
  technicalCategoryTree.value = [
    {
      id: 'tc_1',
      label: '基础数据',
      children: [
        { id: 'tc_1_1', label: '字典表' },
        { id: 'tc_1_2', label: '配置表' },
      ]
    },
    {
      id: 'tc_2',
      label: '业务数据',
      children: [
        { id: 'tc_2_1', label: '业务主表' },
        { id: 'tc_2_2', label: '业务子表' },
        { id: 'tc_2_3', label: '业务关联表' },
      ]
    },
    {
      id: 'tc_3',
      label: '统计数据',
      children: [
        { id: 'tc_3_1', label: '汇总表' },
        { id: 'tc_3_2', label: '事实表' },
        { id: 'tc_3_3', label: '维度表' },
      ]
    },
  ]
  
  // 构建分类选项
  businessCategoryOptions.value = buildCategoryOptions(businessCategoryTree.value)
  technicalCategoryOptions.value = buildCategoryOptions(technicalCategoryTree.value)
}

// 构建分类选项
const buildCategoryOptions = (tree: any[]) => {
  return tree.map(node => {
    const option = {
      value: node.id,
      label: node.label,
      children: node.children ? buildCategoryOptions(node.children) : undefined
    }
    return option
  })
}

// 获取数据对象列表
const getDataObjectList = () => {
  loading.value = true
  
  // 模拟接口请求
  setTimeout(() => {
    // 模拟数据
    const mockData = Array.from({ length: 35 }).map((_, index) => {
      const id = `obj_${index + 1}`
      const dataSourceIndex = index % 8
      const dataSourceTypes = ['MySQL', 'Oracle', 'SQLServer', 'PostgreSQL', 'MongoDB', 'Redis', 'Hive', 'HBase']
      const dataSourceType = dataSourceTypes[dataSourceIndex]
      const dataSourceName = `${dataSourceType}数据源${dataSourceIndex + 1}`
      const dataSourceId = `ds_${dataSourceIndex + 1}`
      
      const objectTypeIndex = index % 6
      const objectTypes = ['TABLE', 'VIEW', 'PROCEDURE', 'FUNCTION', 'TRIGGER', 'SEQUENCE']
      const objectType = objectTypes[objectTypeIndex]
      const objectName = `${objectType.toLowerCase()}_example_${index + 1}`
      
      const businessCategoryIndex = index % 4
      const businessCategories = ['销售管理', '生产管理', '库存管理', '财务管理']
      const businessCategory = businessCategories[businessCategoryIndex]
      
      const technicalCategoryIndex = index % 3
      const technicalCategories = ['基础数据', '业务数据', '统计数据']
      const technicalCategory = technicalCategories[technicalCategoryIndex]
      
      return {
        id,
        objectName,
        objectType,
        dataSourceId,
        dataSourceName,
        dataSourceType,
        schemaName: objectType === 'TABLE' ? `schema_${dataSourceIndex + 1}` : '',
        businessCategory,
        technicalCategory,
        columnCount: Math.floor(Math.random() * 30) + 3,
        description: `这是一个${getObjectTypeLabel(objectType)}示例，ID为${id}`,
        createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toLocaleString(),
        createUser: 'admin',
        updateTime: new Date(Date.now() - Math.floor(Math.random() * 1000000000)).toLocaleString(),
        updateUser: 'admin',
      }
    })
    
    // 模拟搜索过滤
    let filteredData = [...mockData]
    
    if (searchForm.objectName) {
      filteredData = filteredData.filter(item => item.objectName.includes(searchForm.objectName))
    }
    
    if (searchForm.objectType) {
      filteredData = filteredData.filter(item => item.objectType === searchForm.objectType)
    }
    
    if (searchForm.dataSourceId) {
      filteredData = filteredData.filter(item => item.dataSourceId === searchForm.dataSourceId)
    }
    
    if (searchForm.categoryId && searchForm.categoryType) {
      if (searchForm.categoryType === 'business') {
        filteredData = filteredData.filter(item => item.businessCategory.includes(searchForm.categoryId))
      } else if (searchForm.categoryType === 'technical') {
        filteredData = filteredData.filter(item => item.technicalCategory.includes(searchForm.categoryId))
      }
    }
    
    // 模拟分页
    const start = (queryParams.pageNum - 1) * queryParams.pageSize
    const end = start + queryParams.pageSize
    const pageData = filteredData.slice(start, end)
    
    tableData.value = pageData
    total.value = filteredData.length
    loading.value = false
  }, 500)
}

// 数据源选择
const handleDataSourceSelect = (data: any) => {
  if (data.type === 'root') {
    // 点击根节点，清除数据源过滤
    currentDataSource.value = null
    searchForm.dataSourceId = ''
  } else if (data.type === 'source') {
    // 点击数据源节点，设置当前数据源
    currentDataSource.value = data
    searchForm.dataSourceId = data.id
  }
  
  // 清除分类选择
  currentCategory.value = null
  searchForm.categoryId = ''
  searchForm.categoryType = ''
  
  // 重新查询
  queryParams.pageNum = 1
  getDataObjectList()
}

// 分类选择
const handleCategorySelect = (data: any) => {
  // 设置当前分类
  currentCategory.value = data
  searchForm.categoryId = data.label
  searchForm.categoryType = categoryTabActive.value
  
  // 清除数据源选择
  currentDataSource.value = null
  searchForm.dataSourceId = ''
  
  // 重新查询
  queryParams.pageNum = 1
  getDataObjectList()
}

// 搜索事件
const handleSearch = () => {
  queryParams.pageNum = 1
  getDataObjectList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof typeof searchForm] = ''
  })
  
  // 清除选择状态
  currentDataSource.value = null
  currentCategory.value = null
  
  // 清除树选择
  nextTick(() => {
    dataSourceTreeRef.value?.setCurrentKey(null)
  })
  
  queryParams.pageNum = 1
  getDataObjectList()
}

// 分页事件
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getDataObjectList()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val
  getDataObjectList()
}

// 添加数据对象
const handleAdd = () => {
  // 清除上次的表单数据
  Object.assign(editForm, defaultEditForm)
  
  // 预设数据源（如果有当前选中的数据源）
  if (currentDataSource.value) {
    editForm.dataSourceId = currentDataSource.value.id
    editForm.dataSourceName = currentDataSource.value.label
    editForm.dataSourceType = currentDataSource.value.dbType
  }
  
  // 添加一个默认的ID字段
  editForm.columns = [{
    name: 'id',
    type: 'INTEGER',
    length: '',
    nullable: false,
    isPk: true,
    comment: '主键ID'
  }]
  
  // 显示弹窗
  editDialogVisible.value = true
}

// 查看详情
const handleView = (row: any) => {
  router.push({ name: 'DataObjectDetail', query: { id: row.id, mode: 'view' } })
}

// 编辑数据对象
const handleEdit = (row: any) => {
  // 清除上次的表单数据
  Object.assign(editForm, defaultEditForm)
  
  // 填充当前数据
  editForm.id = row.id
  editForm.objectName = row.objectName
  editForm.objectType = row.objectType
  editForm.dataSourceId = row.dataSourceId
  editForm.dataSourceName = row.dataSourceName
  editForm.dataSourceType = row.dataSourceType
  editForm.schemaName = row.schemaName
  editForm.businessCategory = row.businessCategory
  editForm.technicalCategory = row.technicalCategory
  editForm.description = row.description
  
  // 模拟获取字段数据
  setTimeout(() => {
    // 模拟字段数据
    editForm.columns = Array.from({ length: Math.floor(Math.random() * 5) + 2 }).map((_, index) => {
      const isPk = index === 0
      return {
        name: isPk ? `id` : `field_${index + 1}`,
        type: isPk ? 'INTEGER' : ['VARCHAR', 'INTEGER', 'DECIMAL', 'DATETIME'][Math.floor(Math.random() * 4)],
        length: isPk ? '' : (['VARCHAR'].includes(isPk ? 'INTEGER' : ['VARCHAR', 'INTEGER', 'DECIMAL', 'DATETIME'][Math.floor(Math.random() * 4)]) ? '255' : ''),
        nullable: !isPk,
        isPk,
        comment: isPk ? '主键ID' : `字段${index + 1}的说明`
      }
    })
  }, 300)
  
  // 显示弹窗
  editDialogVisible.value = true
}

// 查看字段信息
const handleViewColumns = (row: any) => {
  router.push({ name: 'DataObjectDetail', query: { id: row.id, mode: 'view', tab: 'columns' } })
}

// 查看血缘关系
const handleViewLineage = (row: any) => {
  router.push({ name: 'DataLineage', query: { id: row.id, name: row.objectName } })
}

// 删除数据对象
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `是否确认删除数据对象 "${row.objectName}"？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 模拟删除操作
      setTimeout(() => {
        const index = tableData.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          tableData.value.splice(index, 1)
          total.value--
        }
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }, 300)
    })
    .catch(() => {
      // 取消删除
    })
}

// 同步元数据
const handleSync = () => {
  if (!currentDataSource.value) {
    ElMessage.warning('请先选择数据源')
    return
  }
  
  // 设置采集表单默认值
  collectForm.dataSourceId = currentDataSource.value.id
  
  // 打开采集对话框
  collectDialogVisible.value = true
}

// 采集元数据
const handleCollect = () => {
  collectDialogVisible.value = true
}

// 提交采集任务
const submitCollect = () => {
  if (!collectForm.dataSourceId) {
    ElMessage.warning('请选择数据源')
    return
  }
  
  if (collectForm.objectTypes.length === 0) {
    ElMessage.warning('请至少选择一种对象类型')
    return
  }
  
  collectLoading.value = true
  
  // 模拟接口调用
  setTimeout(() => {
    collectLoading.value = false
    collectDialogVisible.value = false
    progressDialogVisible.value = true
    
    // 重置进度
    collectProgress.value = 0
    collectFailed.value = false
    
    // 模拟进度更新
    const timer = setInterval(() => {
      collectProgress.value += Math.floor(Math.random() * 10) + 1
      
      if (collectProgress.value >= 100) {
        collectProgress.value = 100
        clearInterval(timer)
        
        // 生成随机结果
        collectResult.table = collectForm.objectTypes.includes('TABLE') ? Math.floor(Math.random() * 50) + 10 : 0
        collectResult.view = collectForm.objectTypes.includes('VIEW') ? Math.floor(Math.random() * 20) + 5 : 0
        collectResult.procedure = collectForm.objectTypes.includes('PROCEDURE') ? Math.floor(Math.random() * 15) + 3 : 0
        collectResult.function = collectForm.objectTypes.includes('FUNCTION') ? Math.floor(Math.random() * 10) + 2 : 0
        collectResult.total = collectResult.table + collectResult.view + collectResult.procedure + collectResult.function
      }
    }, 300)
  }, 1000)
}

// 刷新列表
const refreshList = () => {
  progressDialogVisible.value = false
  getDataObjectList()
}

// 取消编辑
const cancelEdit = () => {
  editDialogVisible.value = false
}

// 保存数据对象
const saveObject = (goToDetail = false) => {
  editFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    
    // 表单校验成功
    submitLoading.value = true
    
    // 模拟保存请求
    setTimeout(() => {
      submitLoading.value = false
      
      // 生成ID（如果是新建）
      if (!editForm.id) {
        editForm.id = `obj_${Date.now()}`
      }
      
      // 保存成功提示
      ElMessage({
        type: 'success',
        message: editForm.id ? '更新成功' : '创建成功'
      })
      
      // 刷新列表
      getDataObjectList()
      
      // 关闭弹窗或跳转
      if (goToDetail) {
        editDialogVisible.value = false
        // 跳转到详情页
        router.push({ 
          name: 'DataObjectDetail', 
          query: { 
            id: editForm.id, 
            mode: 'edit',
            tab: 'columns'
          } 
        })
      } else {
        editDialogVisible.value = false
      }
    }, 800)
  })
}

// 跳转到详情页进行字段高级编辑
const goToDetailForColumns = () => {
  // 如果是新建，先保存
  if (!editForm.id) {
    ElMessageBox.confirm(
      '需要先保存基本信息才能进行高级编辑，是否继续？',
      '提示',
      {
        confirmButtonText: '保存并继续',
        cancelButtonText: '取消',
        type: 'info',
      }
    )
      .then(() => {
        saveObject(true)
      })
      .catch(() => {
        // 取消操作
      })
    return
  }
  
  // 关闭弹窗
  editDialogVisible.value = false
  
  // 跳转到详情页，设置tab参数为columns
  router.push({ 
    name: 'DataObjectDetail', 
    query: { 
      id: editForm.id, 
      mode: 'edit',
      tab: 'columns'
    } 
  })
}

// 初始化
onMounted(() => {
  initDataSourceTree()
  initCategoryTree()
  getDataObjectList()
})
</script>

<style scoped>
.category-tabs :deep(.el-tabs__header) {
  margin-bottom: 10px;
}

.category-tabs :deep(.el-tree-node__content) {
  height: 32px;
}
</style> 